package com.upload.controller;

import com.alibaba.fastjson.JSONObject;
import com.upload.bean.myNative.UploadHistoryBean;
import com.upload.domain.Document;
import com.upload.repository.DocumentRepository;
import com.upload.util.GetMd5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by STARF on 2017/3/20.
 */
@RestController
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Value("${unAuditedPath}")
    private String unAuditedPath;

    //文件上传相关代码
    @PostMapping(value = "api/upload")
    @ResponseBody
    public String upload(
            HttpServletRequest request,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "unionid") String unionid,
            @RequestParam(value = "college") String college,
            @RequestParam(value = "profession") String profession,
            @RequestParam(value = "subject_code") String subject_code,
            @RequestParam(value = "time") int time) {

        System.out.println("------------文件上传---------------");

        System.out.println(request.getScheme()+"://"+ request.getServerName() + ":" + request.getServerPort()+request.getRequestURI()+"?"+request.getQueryString());

        System.out.println("requestUri = " + request.getRequestURI());
        System.out.println("requestQueryString = " + request.getQueryString());
        System.out.println("requestServletPath = " + request.getServletPath());
        System.out.println("requestContextPath = " + request.getContextPath());
        System.out.println("requestRemoteUser = " + request.getRemoteUser());


        System.out.println(file);
        if (file == null) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);

        String timeString = Integer.toString(time);

        //文件重命名
        String newFileName = time+"-"+college+"-"+subject_code+"-"+profession+suffixName;
        int i = 1;
        while (documentRepository.countByFileName(newFileName)>0){
            i++;
            newFileName = time+"-"
                    +college+subject_code+"-"+profession+"("+timeString+")"+suffixName;
        }
        File dest = new File(unAuditedPath + newFileName);
//        System.out.println(newFileName);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);   //文件拷贝
            //获取MD5摘要
            GetMd5Util getMd5Util = new GetMd5Util();
            String md5 = getMd5Util.getMd5(dest);
            System.out.println("MD5============================"+md5);
            if(documentRepository.countByMd5(md5) != 0){
                System.out.println(newFileName+"----文件已存在！");
                return "上传失败，该文件已存在！";
            }

            //上传记录
            Document document = new Document();
            document.setMd5(md5);
            document.setUploadUnionid(unionid);
            document.setCollege(college);
            document.setProfession(profession);
            document.setSubjectCode(subject_code);
            document.setTime(timeString);
            document.setUploadDate(new Date());
            document.setFileName(newFileName);
            document.setFilePath(unAuditedPath+newFileName);
            documentRepository.save(document);

            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    //用户上传记录列表
    @PostMapping(value = "api/history")
    @ResponseBody
    public List<UploadHistoryBean> getUploadHistory(@RequestBody String unionid){

        JSONObject jsonObject = (JSONObject) JSONObject.parse(unionid);
        String uploadUnionid = jsonObject.getString("unionid");

        List<UploadHistoryBean> uploadHistoryBeanList = new LinkedList<>();
        Iterator<Document> documentIterator = documentRepository.findByUploadUnionid(uploadUnionid).iterator();

        while (documentIterator.hasNext()) {
            Document document = documentIterator.next();
            UploadHistoryBean getList = new UploadHistoryBean();
            getList.setId(document.getId());
            getList.setFileName(document.getFileName());
            getList.setUploadDate(new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(document.getUploadDate()));
            getList.setStatus(document.getStatus());
            uploadHistoryBeanList.add(getList);
        }
        return uploadHistoryBeanList;
    }

    @Autowired
    private DocumentRepository documentRepository;

}
